package com.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.server.common.QueryPageParam;
import com.server.common.Result;
import com.server.entity.*;
import com.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@PostMapping("/login")
	public Result login(@RequestBody Map map) {
		List<User> list=userService.lambdaQuery()
				.eq(User::getId,map.get("id"))
				.eq(User::getPassword, map.get("password")).list();
		return !list.isEmpty() ?Result.suc(list.get(0),1L):Result.fail();
	}

	@PostMapping("/signup")
	public Result signup(@RequestBody SignupRequest signupRequest) {
		User user= signupRequest.getForm();
		System.out.println(user);
		String email = user.getEmail();  // 获取邮箱
		String captchaInput = signupRequest.getCaptcha();  // 获取用户输入的验证码

		// 从 Redis 获取存储的验证码
		String redisCaptcha = redisTemplate.opsForValue().get( email);

		if (redisCaptcha == null) {
			// 验证码不存在，可能是验证码过期或者从未发送过
			return Result.fail();
		}
		if (!redisCaptcha.equals(captchaInput)) {
			// 用户输入的验证码与存储的验证码不匹配
			return Result.fail();
		}

		userService.save(user);
		return Result.suc(user,1L);
	}

	@GetMapping("/list")
	public List<User> list(){
		return userService.list();
	}

	@PostMapping("/save")
	public Result save(@RequestBody User user){
		if(userService.save(user))
			return Result.suc(user, 1L);
		else
			return Result.fail();
	}

	@PostMapping("/modify")
	public boolean modify(@RequestBody User user){
		return userService.updateById(user);
	}

	@PostMapping("/saveORmodify")
	public Result saveORmodify(@RequestBody User user){
		if(userService.saveOrUpdate(user))
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}

	@PostMapping("/delete")
	public Result delete(@RequestBody Map<String, List<Integer>> requestMap){
		List<Integer> ids = requestMap.get("ids");
		boolean res = true;
		for(Integer id : ids){
			System.out.println(id);
			if(id!=null)
				res=res&userService.removeById(id);
		}
		if(res)
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}

	@PostMapping("/querylike")
	public Result querylike(@RequestBody QueryPageParam query) {

		// 创建分页对象
		Page<User> page = new Page<>(query.getPageNum(), query.getPageSize());

		// 获取查询参数
		HashMap<String, Object> map = query.getParam();

		// 创建条件构造器
		LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		// 动态拼接条件
		String name = map.get("name") != null ? map.get("name").toString().trim() : "";
		String email = map.get("email") != null ? map.get("email").toString().trim() : "";
		String id = map.get("id") != null ? map.get("id").toString().trim() : "";
		System.out.println(name+" "+email+" "+id);
		if (!name.isEmpty()) {
			lambdaQueryWrapper.like(User::getName, name);
		}
		if (!email.isEmpty()) {
			lambdaQueryWrapper.like(User::getEmail, email);
		}
		if (!id.isEmpty()) {
			lambdaQueryWrapper.eq(User::getId, id); // 精确查询
		}

		// 执行查询
		IPage<User> res = userService.pageC(page, lambdaQueryWrapper);
		// 返回结果
		return Result.suc(res.getRecords(), res.getTotal());
	}

	@PostMapping("/addbalance")
	public Result addBalance(@RequestBody Map<String, Object> requestMap) {
		System.out.println(requestMap);
		Integer uid = (Integer) requestMap.get("uid");
		Object balanceObj = requestMap.get("balance");
		BigDecimal balance = BigDecimal.valueOf(0);  // 默认值为0
		if (balanceObj instanceof Number) {
			balance = new BigDecimal(balanceObj.toString());  // 将数字转换为 BigDecimal
		}
		System.out.println(balance);
		User user = userService.getById(uid);
		balance=balance.add(user.getBalance());
		user.setBalance(balance);
		userService.updateById(user);
		return Result.suc(user,1L);
	}
}
